import { createStore } from 'vuex'
import AuthService from '../services/auth.service'
import axios from 'axios'

export default createStore({
  state: {
    user: null,
    token: localStorage.getItem('token') || null
  },
  mutations: {
    setUser(state, user) {
      state.user = user
    },
    setToken(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    logout(state) {
      state.user = null
      state.token = null
      localStorage.removeItem('token')
    }
  },
  actions: {
    async login({ commit }, credentials) {
      try {
        const response = await AuthService.login(credentials)
        commit('setUser', response.user)
        commit('setToken', response.token)
        return response
      } catch (error) {
        throw error
      }
    },
    async register({ commit }, userData) {
      try {
        const response = await AuthService.register(userData)
        return response
      } catch (error) {
        throw error
      }
    },
    async updateProfile({ commit }, userData) {
      try {
        const response = await axios.put('/api/user/profile', userData)
        commit('setUser', response.data)
        return response
      } catch (error) {
        throw error
      }
    },
    async changePassword({ commit }, passwordData) {
      try {
        await axios.put('/api/user/password', passwordData)
      } catch (error) {
        throw error
      }
    }
  },
  getters: {
    isAuthenticated: state => !!state.token,
    currentUser: state => state.user
  }
}) 